package com.coding.easier.util;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author D丶Cheng
 * @Description url 工具类
 * @Date 2021/11/15 9:39
 **/
public class UrlUtils {
    public static final String QUESTION_MARK = "?";
    public static final String AND_MARK = "&";
    public static final String EQUAL_MARK = "=";

    private List<Item> parameters;
    private String baseUrl;

    public UrlUtils(String baseUrl) {
        this.baseUrl = baseUrl;
        parameters = new ArrayList<>();
    }

    public List<Item> getParameters() {
        return parameters;
    }

    public void setParameters(List<Item> parameters) {
        this.parameters = parameters;
    }

    public String getBaseUrl() {
        return baseUrl;
    }

    public void setBaseUrl(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    class Item {
        private String key;
        private String value;

        public Item(String key, String value) {
            this.key = key;
            this.value = value;
        }

        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }

    /**
     * 向url链接追加参数（会覆盖已经有的参数）
     *
     * @return
     */
    public UrlUtils addQueryParameter(String name, String... values) {
        for (String value : values) {
            parameters.add(new Item(name, value));
        }
        return this;
    }

    public String build() {
        if (parameters.isEmpty()) {
            return baseUrl;
        }

        StringBuilder stringBuilder = new StringBuilder(baseUrl);
        parameters.forEach((item) -> {
            if (stringBuilder.indexOf(QUESTION_MARK) == -1) {
                stringBuilder.append(QUESTION_MARK);
            }
            else {
                stringBuilder.append(AND_MARK);
            }
            stringBuilder.append(item.getKey())
                    .append(EQUAL_MARK)
                    .append(item.getValue());
        });
        return stringBuilder.toString();
    }
}
